package com.example.demo.listnode;

import com.example.demo.model.ListNode;

/**
 * 旋转链表
 * https://leetcode.cn/problems/rotate-list/description/
 */
public class RotateNode {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) return head;

        int len = 0;             //链表的长度
        ListNode tail = null;  //尾节点
        for (ListNode p = head; p != null; p = p.next) {
            tail = p;
            len++;
        }

        k %= len;
        ListNode p = head;
        for (int i = 0; i < len - k - 1; i++) {
            p = p.next;   //找到链表的第n-k个节点
        }
        tail.next = head;
        head = p.next;
        p.next = null;
        return head;  //返回新的头节点
    }
}
